package com.vecspace.web.filter;

import java.io.IOException; 
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.vecspace.utils.UUIDUtil;
import com.vecspace.web.HttpContext;
import com.vecspace.web.HttpContextThreadLocal;
import com.vecspace.web.servlet.model.HttpServletRequestWrapperEx;


/**将request，response放到HttpContextThreadLocal中，以便在service中取用
 */
public class ContextFilter implements Filter{
	 
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		//testLogin();
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		response.setHeader("token", "dayu-" + UUIDUtil.createUUID());
		request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));  //设置spring mvc中试图（比如freemarker）的语言为zh_CN
		
		HttpContext httpContext = HttpContextThreadLocal.getHttpContext();
		httpContext.setHttpRequest(request);
		httpContext.setHttpResponse(response);		
		chain.doFilter(new HttpServletRequestWrapperEx(request), response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		
	}

}
